<?php

namespace App\Repositories\Impl;

use App\Models\VolunteerActivity;
use App\Repositories\Contracts\VolunteerActivityRepository;
use App\Repositories\Transformers\VolunteerActivityListTransformer;
use App\Repositories\Transformers\VolunteerActivityTransformer;

class VolunteerActivityRepositoryImpl implements VolunteerActivityRepository
{
    public function paginate($perPage, $filter)
    {
        if (!empty($filter['keyword'])) {
            $activity = VolunteerActivity::withCount(['volunteerForm' => function ($query) {
                $query->where('audit_status', '1');
            }])->where('title', 'like', '%' . $filter['keyword'] . '%')
                ->orWhere('content', 'like', '%' . $filter['keyword'] . '%')->orderBy('created_at', 'desc')->paginate($perPage);
        } else {
            $activity = VolunteerActivity::withCount(['volunteerForm' => function ($query) {
                $query->where('audit_status', '1');
            }])->orderBy('created_at', 'desc')->paginate($perPage);
        }

        $result = fractal($activity, new VolunteerActivityListTransformer());

        return $result->toArray();

    }

    public function find($id, $columns = ['*'])
    {
        $activity = VolunteerActivity::withCount(['volunteerForm' => function ($query) {
            $query->where('audit_status', '1');
        }])->find($id, $columns);

        $result = fractal($activity, new VolunteerActivityTransformer());

        return $result->toArray();

    }

    public function findByIds($ids)
    {
        return VolunteerActivity::where('id', $ids)->get();
    }

    public function findByFilter($filter, $columns = ['*'])
    {
        return VolunteerActivity::where($filter)->first($columns);
    }

    public function store($data)
    {
        return VolunteerActivity::create($data);
    }

    public function update($data, $id)
    {
        return VolunteerActivity::whereId($id)->updateOrCreate($data);
    }

    public function updateByFilter($data, $where)
    {
        return VolunteerActivity::where($where)->update($data);
    }

    public function delete($id)
    {
        return VolunteerActivity::whereId($id)->delete();
    }
}
